<template>
	<view style="width: 100vw;">
		<view class="top_view" :style="{'margin-top':clientType=='pda'?'0px':'30px','margin-bottom':clientType=='pda'?'0px':'40px'}">
			<view class="top_view_image">
				<image class="top_image" :src="picappicon" mode="aspectFit"></image>
			</view>
			{{title}}
		</view>
		<view>
			<form @submit="loginbtn" >
				
				<view class="center_view">
					<view style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;margin-bottom: 10px;">
						<view :class="logintype=='pwd'?'pwd-d':'pwd'" @click="changetype('pwd')">
							<view :class="logintype=='pwd'?'botbor-d':''">{{loginObj.pwd}}</view>
						</view>
						<view :class="logintype!='pwd'?'pwd-d':'pwd'" @click="changetype('code')">
							<view :class="logintype!='pwd'?'botbor-d':''">{{loginObj.sms}}</view>
						</view>
					</view>
					
					<view v-if="logintype=='pwd'" class="center_input_item">
						<view class="second_item">
							<image class="center_image_user" src="../../static/images/telephone.png"></image>
							<input name="accountid" class="center_text" :placeholder="loginObj.inacount" placeholder-style="font-size:12px" :value="accountid"></input>
						</view>
						
						<view class="line"></view>
						<view class="third_item">
							<image class="center_image_password" src="../../static/images/account_top.png"></image>
							<input name="password" class="center_text" :placeholder="loginObj.inpwd" placeholder-style="font-size:12px" :value="password"
							 :password="isshowpwd"></input>
							<image class="get_codes" :src="pwd" @click="showpwd(isshowpwd)"></image>
						</view>
						<view class="line"></view>
					</view>
					
					<view v-else class="center_input_item">
						<view class="second_item">
							<image class="center_image_user" src="../../static/images/telephone.png"></image>
							<input name="phone" class="center_text" :placeholder="loginObj.inphone" placeholder-style="font-size:12px" v-model="phone"></input>
						</view>
						
						<view class="line"></view>
						<view class="third_item">
							<image class="center_image_password" src="../../static/images/account_top.png"></image>
							<input name="code" class="center_text" :placeholder="loginObj.incode" placeholder-style="font-size:12px" v-model="code"></input>
							<button style="min-width: 80px;padding: 0 5px;border: none;" class="iv"
							    @click="getCode" :class="codeTime>0 ?'bg-d':'bg'"> {{codeTime>0 ? codeTime+'s': loginObj.getcode }}
							</button>
						</view>
						<view class="line"></view>
					</view>
					
					<view>
						<button class="register" form-type="submit">{{openpageBtnInfo.btnText}}</button>
					</view>
					<view class="forgetpwd" v-if="isHaveSavePWD && logintype=='pwd'">
						<view v-if="isremeberpwd=='true'">
							<checkbox class="forgetpwdtxt" checked="true" @click="remeberpwd(isremeberpwd)">{{loginObj.rmpwd}}</checkbox>
						</view>
						<view v-else>
							<checkbox class="forgetpwdtxt" @click="remeberpwd(isremeberpwd)">{{loginObj.rmpwd}}</checkbox>
						</view>
						<view v-if="JSON.stringify(i18nArr)!='[]'" style="display: flex;  align-items: center; padding: 2px 12px;font-size: 14px;color: #333;background: #f0f0f0;border-radius: 5px;">
							<picker @change="bindPickerChange($event)"
									:value="i18nArrIndex" 
									:range="i18nArr" 
									:range-key="'name'">
								<view>{{i18nArr[i18nArrIndex].name}}</view>
							</picker>
						</view>
					</view>
					
					<!-- #ifdef MP-WEIXIN -->
					<view style="position: absolute;bottom: 10px;width:calc(100vw - 80px) ">
						<button type="default"   @click="getinfo" >{{loginObj.wx}}</button>
					</view>
					<!-- #endif -->
				</view>
			</form>
		</view>
	</view>
</template>



<script>
	export default {
		data() {
			return {
				pwd: '../../static/images/tms/ic_eye_close.png',
				isshowpwd: true,
				password: '',
				accountid: '',
				isremeberpwd: '',
				picappicon: '',
				isHaveSavePWD: '',
				openpageBtnInfo:[],
				modId:'appsj_logon',
				menuId:'',
				pageName:'appsj_logon',
				templetName:'appsj_logon',
				title:'',
				lr:{},
				mac:'',
				machineName:'',
				clientType:'',
				logintype:'pwd',
				phone:'',
				code:'',
				codeTime:0,
				openid:'',
				nickname:'',
				i18nArr:[],
				i18nArrIndex:0,
				loginObj:{},
				divlogin:{},
				cnObj:{'pwd':'账号登录','sms':'手机登录','wx':'微信登录','rmpwd':'记住密码','inacount':'请输入账号',
						'inpwd':'请输入密码','inphone':'请输入手机号','incode':'请输入验证码','getcode':'获取验证码'},
				enObj:{'pwd':'Acount login','sms':'Phone login','wx':'Wechat login','rmpwd':'Remember password','inacount':'Your account number',
						'inpwd':'Your password','inphone':'Your phone number','incode':'Your verification code','getcode':'Send Code'}
			};
		},
		

		components: {},
		props: {},

		//张总密码001
		onLoad: async function(options) {
			var that = this
			this.clientType = uni.getStorageSync('clientType')
			var pageName = uni.getStorageSync('loginpageName')
			if(pageName == undefined || pageName == ''){
				uni.reLaunch({url:'../first/first'})
			}
			var machineName = ''
			var mac = ''
			var ip = ''
			uni.getSystemInfo({
				success:function(e){
					machineName = e.deviceBrand + ' ' + e.deviceModel + ' ' + e.deviceType
					that.mac = e.deviceId
				}
			})
			
			// #ifdef APP-PLUS
			    console.log("UUID: " + plus.device.uuid);
				that.mac = plus.device.uuid
				
			// #endif
			
			// that.mac = '111111' //这个做测试用 后期要改
			
			that.machineName = machineName
			var injson = that.$PageInfo(mac, machineName)
			console.log(injson)
			
			var url = getApp().globalData.app_address + '?method=saas_PageInfo&parse=json'
			const { data: result } = await that.$post2(url, injson);
			console.log(JSON.parse(JSON.stringify(result)))
			
			if(result.rtn==1){
				var rd = result.data
				that.divlogin = rd
				let i18nArr = rd.page.i18nArr==undefined?[]:rd.page.i18nArr
				that.i18nArr= i18nArr
				let i18nStr = uni.getStorageSync('i18n')===''?'cn':uni.getStorageSync('i18n')
				if(i18nStr === 'cn'){
					this.loginObj = this.cnObj
					that.title = that.divlogin.page.title
					// uni.setLocale('cn') //APP不支持
				}else{
					uni.setNavigationBarTitle({title:'Login'})
					this.loginObj = this.enObj
					// uni.setLocale('en')
				}
				console.log('i18nStr',i18nStr)
				if(i18nArr.length > 0 ){
					i18nArr.forEach((val,index)=>{
						if(val.i18n == i18nStr){
							that.i18nArrIndex = index
						}
					})
					if( i18nStr!=='cn'){
						let ininjson = that.$requestI18n()
						var inurl = getApp().globalData.app_address + '?method=saas_I18n&parse=json'
						const { data: inresult } = await that.$post2(inurl, ininjson);
						if(inresult.rtn == 1){
							//App端为原生的plus.storage，无大小限制，不是缓存，是持久化的
							//微信小程序单个 key 允许存储的最大数据长度为 1MB，所有数据存储上限为 10MB
							uni.setStorageSync('i18nArr', inresult.data)
							that.title = that.$translg(that.divlogin.page.title,inresult.data)
						}
					}
					
				}
				
				let i18nArr2 = uni.getStorageSync('i18nArr')
				
				that.picappicon = getApp().globalData.pic_address +rd.page.logoPic
				that.isHaveSavePWD  = rd.page.isHaveSavePWD
				
				var btns = rd.btns
				if(JSON.stringify(btns) != '[]'){
					btns.forEach((val)=>{
						if(val.name == 'logon'){
							if(i18nStr === 'en' && i18nArr!=undefined){
								val.btnText = that.$translg(val.btnText,i18nArr2)
							}
							that.openpageBtnInfo = val
						}
					})
				}
			}
		},
		
	
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function(options) {
			var that = this
			var isremeberpwd = uni.getStorageSync('isremeberpwd');
			var password = uni.getStorageSync('password');
			var accountid = uni.getStorageSync('accountid');
			that.accountid = accountid
			if (isremeberpwd == 'true') {
				that.password = password
				that.isremeberpwd = 'true'
			} else {
				that.isremeberpwd = ''
			}
		},

		methods: {
			
			async bindPickerChange(e){
				var that = this
				let value = e.detail.value
				this.i18nArrIndex = value
				let i18nStr = this.i18nArr[value].i18n
				uni.setStorageSync('i18n',i18nStr)
				if(i18nStr === 'cn'){
					this.loginObj = this.cnObj
					that.title = that.divlogin.page.title
					that.openpageBtnInfo.btnText = that.openpageBtnInfo.text
					uni.setLocale('cn')
				}else{
					this.loginObj = this.enObj
					uni.setLocale('en')
				}
				if(i18nStr !== 'cn'){
					let ininjson = that.$requestI18n()
					var inurl = getApp().globalData.app_address + '?method=saas_I18n&parse=json'
					const { data: inresult } = await that.$post2(inurl, ininjson);
					if(inresult.rtn == 1){
						uni.setStorageSync('i18nArr', inresult.data)
						that.title = that.$translg(that.divlogin.page.title,inresult.data)
						that.openpageBtnInfo.btnText = that.$translg(that.openpageBtnInfo.btnText,inresult.data)
					}
					
				}
			},
			
			async getinfo(){
				var that = this
				var code = ''
				var openid = ''
				var nickname = ''
				
				uni.getUserInfo({
					desc: "用于完善会员资料",
					success: (res) => {
						var userInfo = res.userInfo;
						nickname = userInfo.nickName
						that.nickname = nickname
					}
				});
				const loginResult = await uni.login();
				code = loginResult[1].code
				var openidresult = await uni.request({
					url: 'https://www.hbxtwl.com/mxdzapi/getopenidnbmtglpt?code='+code,
					data: {},
					method: 'GET',
					header: {'content-type': 'application/json'}
				})
				openid = openidresult[1].data.openid
				that.openid = openid
				await new Promise(resolve => setTimeout(resolve, 500));
				
				var injson = that.$wxLogin(that.mac, that.machineName, openid, nickname)
				console.log(injson)
				var url = getApp().globalData.app_address + '?method=saas_UserLoginByWeChat&parse=json'
				const { data: res2 } = await that.$post2(url, injson);
				console.log(res2)
				if(res2.rtn == -1){
					uni.showModal({
						title: '提示',
						content: res2.message,
						showCancel:false
					})
					return
				}else{
					that.loginres(res2.data, '', res2.data.loginId)
				}
			},
			
			changetype(type){
				 this.logintype = type
			},
			
			async getCode(){
				var that = this
				let msg = that.$isMobileNumber(that.phone)
				if(msg != ''){
					uni.showModal({
						title: '提示',
						content: msg,
						showCancel:false
					})
					return
				}
				if(that.codeTime>0)return
				var injson = that.$saas_UserLoginBySMS_GetPin(that.mac, that.machineName, that.phone)
				var url = getApp().globalData.app_address + '?method=saas_UserLoginBySMS_GetPin&parse=json'
				const { data: res2 } = await that.$post2(url, injson);
				console.log(res2)
				that.codeTime = 60
				let timer = setInterval(()=>{
					if(that.codeTime >= 1){
						that.codeTime --
					}else{
						clearInterval(timer)
					}
				},1000)
			},
			
			showpwd(isshowpwd) {
				var that = this
				var isshowpwd = isshowpwd
				if (isshowpwd) {
					that.pwd = '../../static/images/tms/ic_eye_open.png'
					that.isshowpwd = false
				} else {
					that.pwd = '../../static/images/tms/ic_eye_close.png'
					that.isshowpwd = true
				}
			},

			remeberpwd(isremeberpwd) {
				console.log(isremeberpwd)
				var that = this
				var isremeberpwd = isremeberpwd;
				if (isremeberpwd == 'true') {
					that.isremeberpwd = ''
					uni.setStorageSync('isremeberpwd', '');
				} else {
					that.isremeberpwd = 'true'
					uni.setStorageSync('isremeberpwd', 'true');
				}
			},
			
			
			async loginbtn(res) {
				var that = this
				console.log(res)
				var loginId = res.detail.value.accountid;
				var password = res.detail.value.password;
				var modId = that.modId
				var pageName = that.pageName
				var templetName = that.templetName
				var menuId = that.menuId
				var machineName = that.machineName
				var mac = that.mac
				var ip = ''
				if(loginId=='666666' && password=='RootSoft'){
					
					uni.setStorageSync('productCodePre',uni.getStorageSync('productCode'))
					uni.setStorageSync('projectNamePre',uni.getStorageSync('projectName'))
					uni.setStorageSync('accountNamePre',uni.getStorageSync('accountName'))
					
					const keys = uni.getStorageInfoSync().keys;
					keys.forEach(key => {
						if(key!='productCodePre' && key!='projectNamePre' && key!='accountNamePre' && key!='projectList'){
							uni.removeStorageSync(key);
						}
					});
					uni.setStorageSync('loginIdPre',loginId)
					uni.reLaunch({
						url:'../first/first'
					})	
					return
				}
				
				if(that.logintype == 'pwd'){
					
					if(that.openid == ''){
						that.pwdlogin(mac, machineName, loginId, password,false)
					}else{
						uni.showModal({
							title: '提示',
							content:'是否通过密码登录并且绑定微信号'+that.nickname,
							showCancel:true,
							cancelText: '取消',
							cancelColor: '#999',
							confirmText: '确定',
							confirmColor: '#ff9d29',
							success: res => {
								if (res.confirm) {
									that.pwdlogin(mac, machineName, loginId, password, true)
								}else if (res.cancel) {
									that.pwdlogin(mac, machineName, loginId, password, false)
								}
							}
						})
					}
				}else{
					if(that.openid==''){
						that.smslogin(mac, machineName, false)
					}else{
						 uni.showModal({
							title: '提示',
							content:'是否通过短信登录并且绑定微信号'+that.nickname,
							showCancel:true,
							cancelText: '取消',
							cancelColor: '#999',
							confirmText: '确定',
							confirmColor: '#ff9d29',
							success: res => {
								if (res.confirm) {
								  that.smslogin(mac, machineName, true)
								}else if (res.cancel) {
								  that.smslogin(mac, machineName, false)
								}
							}
						})
					}
				}
			},
		
		
			loginres(lr,password,loginId){
				var that = this
				uni.setStorageSync('sessionId',lr.sessionId)
				uni.setStorageSync('userId',lr.userId)
				uni.setStorageSync('userName',lr.userName)
				uni.setStorageSync('appVersion',lr.appVersion)
				uni.setStorageSync('accountid', loginId);
				uni.setStorageSync('wx_appid', lr.wx_appid);
				uni.setStorageSync('wx_serviceid', lr.wx_serviceid);
				uni.setStorageSync('partnerCode', lr.partnerCode!=undefined?lr.partnerCode:'');
				uni.setStorageSync('partnerName', lr.partnerName!=undefined?lr.partnerName:'');
				uni.setStorageSync('ckdm',lr.ckdm!=undefined?lr.ckdm:'')
				uni.setStorageSync('mddm',lr.mddm!=undefined?lr.mddm:'')
				uni.setStorageSync('hardwareCode',that.mac)
				var isremeberpwd = uni.getStorageSync('isremeberpwd');
				if (isremeberpwd == 'true' && that.logintype=='pwd') {
					uni.setStorageSync('password', password);
				}
				var clicked = this.openpageBtnInfo.clicked
				var openpageBtnInfo = this.openpageBtnInfo
				var pageName2 = clicked.pageName
				var templetName2 = clicked.templetName
				var expArgs = clicked.expArgs
				if(templetName2 == 'appsj_index' || templetName2 == 'appsj_list' || templetName2 == 'appsj_index_pda'){
					uni.setStorageSync('pageName',pageName2)
					uni.setStorageSync('templetName',templetName2)
					uni.setStorageSync('modid', openpageBtnInfo.powerModId)
					uni.setStorageSync('menuid', openpageBtnInfo.powerModCode)
					uni.setStorageSync('expArgs',expArgs)
					uni.setStorageSync('indexTempletName', templetName2)
					if(templetName2 == 'appsj_index' || templetName2=='appsj_index_pda'){
						uni.switchTab({url:'../index/index'})
					}else if(templetName2 == 'appsj_list'){
						uni.reLaunch({
							url:'../infolist/infolist?templatename='+templetName2+'&pagename='+pageName2+'&menuid='+openpageBtnInfo.powerModCode+'&menuname=首页&modid='+openpageBtnInfo.powerModId
						})
					}
				}
			},
		
			async pwdlogin(mac, machineName, loginId, password, iswx){
				var that = this
				if(iswx){
					var injson = that.$pwdwxLogin(mac, machineName, loginId, password, that.openid, that.nickname)
					var url = getApp().globalData.app_address + '?method=saas_UserLoginByIdForBindWeChat&parse=json'
				}else{
					console.log('mac',mac)
					var injson = that.$Login(mac, machineName, loginId, password)
					var url = getApp().globalData.app_address + '?method=saas_UserLoginById&parse=json'
				}
				console.log(injson)
				const { data: res2 } = await that.$post2(url, injson);
				var result = res2 
				console.log('saas_UserLoginById',result)
				
				if(result.rtn==1){
					var lr = result.data
					that.lr = lr
					loginId = lr.loginId
					var injson =  that.$LoginCheck(mac, machineName, lr, loginId)
					if(result.data.isLoginSMSVerify!=1){
						var iObj = JSON.parse(injson)
						iObj['mobile'] = ''
						iObj['regResult'] = 'nosmsverify'
						iObj['hostMacAll'] = ''
						iObj['hostVolumeID'] = ''
						iObj['hostDiskID'] = ''
						var url = getApp().globalData.app_address + '?method=saas_Login_4UpdateUserDevice&parse=json'
						console.log(iObj)
						const { data: res4 } = await that.$post2(url, JSON.stringify(iObj));
						console.log(res4)
						if(res4.rtn == 1){
							this.loginres(lr, password,loginId)
						}
					}else{
						var url = getApp().globalData.app_address + '?method=saas_Login_1IsNeedSMSCheck&parse=json'
						const { data: res3 } = await that.$post2(url, injson);
						console.log(res3)
						var d = res3.data
						// this.loginres(lr, password,loginId)
						if(res3.rtn == 1){
							if(d.isNeedSMSCheck){
								uni.navigateTo({url:'../smscheck/smscheck?mobile='+d.mobile+'&ij='+injson+'&loginId='+loginId+'&lr='+JSON.stringify(lr)+'&password='+password+'&regResult='+d.regResult+'&openpageBtnInfo='+JSON.stringify(this.openpageBtnInfo)})
							}else{
								var iObj = JSON.parse(injson)
								iObj['mobile'] = d.mobile
								iObj['regResult'] = d.regResult
								iObj['hostMacAll'] = ''
								iObj['hostVolumeID'] = ''
								iObj['hostDiskID'] = ''
								var url = getApp().globalData.app_address + '?method=saas_Login_4UpdateUserDevice&parse=json'
								const { data: res4 } = await that.$post2(url, JSON.stringify(iObj));
								if(res4.rtn == 1){
									this.loginres(lr, password,loginId)
								}
							}
						}
					
					}
				}else{
					uni.showModal({
						title: '提示',
						content: result.message,
						showCancel:false
					})
				}
			},
		
			async smslogin(mac, machineName,iswx){
				var that = this
				if(iswx){
					var injson = that.$smswxLogin(mac, machineName, that.phone, that.code,that.openid, that.nickname)
					var url = getApp().globalData.app_address + '?method=saas_UserLoginBySMSForBindWeChat&parse=json'
				}else{
					var injson = that.$smsLogin(mac, machineName, that.phone, that.code)
					var url = getApp().globalData.app_address + '?method=saas_UserLoginBySMS&parse=json'
				}
				
				const { data: res4 } = await that.$post2(url, injson);
				var result = res4 
				if(result.rtn == 1){
					that.loginres( result.data, '', result.data.loginId)
				}
			}
		}
	};
</script>


<style>
	@import "./register.css";
	.bg-d{background-color:#fd6137;color:#fff;}
	.bg{background-color: cornsilk;color: #666;}
	.pwd-d{width: 50%;color:#ff9d29; display: flex;justify-content: center;padding: 5px 0;}
	.pwd{width: 50%;color:#666;display: flex;justify-content: center;padding: 5px 0;}
	.botbor-d{border-bottom: #ff9d29 solid 2px;}
	.forgetpwd{display: flex;flex-direction: row;justify-content: space-between;}
</style>
